﻿function CompanyViewModel(parent, auth, username) {
    var self = this;

    // non knockout variables - those that are not changable
    self.auth = auth;
    self.username = username;

    // knockout variables
    self.companies = ko.observableArray([]);
    self.myCompanies = ko.observableArray([]);
    self.workingCompany = ko.observable(null);
    self.workingCompanyId = ko.observable(null);
    self.workingCompanyBuffer = ko.observable(new CompanyProfile({ }));
    self.companyAdvancedSearch = ko.observable(new CompanyProfileAdvancedSearch({ }));
    self.companyViewMode = ko.observable("list");
    self.listCompanyViewMode = ko.observable(true);
    self.detailsCompanyViewMode = ko.observable(false);
    self.editCompanyViewMode = ko.observable(false);
    self.advancedSearchCompanyViewMode = ko.observable(false);
    self.selectedIndustryId = ko.observable(null);
    self.selectedCountryId = ko.observable(null); 
    self.selectedCategoryId = ko.observable(-1);
    self.selectedSubcategoryId = ko.observable(-1);
    self.searchType = ko.observable();
    self.pageSize = ko.observable();
    self.industryTags = ko.observableArray([]);
    self.countryTags = ko.observableArray([]);
    self.categoryTags = ko.observableArray([]);
    self.technologyTags = ko.observableArray([]);
    self.keywordTags = ko.observableArray([]);
    self.keyword = ko.observable("");
    self.enterKeyPressed = false;

    //RESET TAGS LISTS
    self.resetTagsLists = function() {
        self.countryTags([]);
        self.industryTags([]);
        self.categoryTags([]);
        self.industryTags([]);
        self.keywordTags([]);
    };

    self.inspectViewMode = ko.computed(function() {
        var mode = self.companyViewMode();
        if (mode == "list") {
            self.listCompanyViewMode(true);
            self.detailsCompanyViewMode(false);
            self.editCompanyViewMode(false);
            self.advancedSearchCompanyViewMode(false);
        } else if (mode == "myList") {
            self.listCompanyViewMode(true);
            self.detailsCompanyViewMode(false);
            self.editCompanyViewMode(false);
            self.advancedSearchCompanyViewMode(false);
        } else if (mode == "details") {
            self.listCompanyViewMode(false);
            self.detailsCompanyViewMode(true);
            self.editCompanyViewMode(false);
            self.advancedSearchCompanyViewMode(false);
        } else if (mode == "edit") {
            self.listCompanyViewMode(false);
            self.detailsCompanyViewMode(false);
            self.editCompanyViewMode(true);
            self.advancedSearchCompanyViewMode(false);
        } else if (mode == "advancedSearch") {
            self.listCompanyViewMode(false);
            self.detailsCompanyViewMode(false);
            self.editCompanyViewMode(false);
            self.advancedSearchCompanyViewMode(true);
        }
    });

    self.select = function(company) {
        self.workingCompany(company);
        self.workingCompanyId(company.Id);
    };
    self.deselect = function() {
        self.workingCompany(null);
    };
    self.selectNew = function() {
        var newCompany = new CompanyProfile({ });
        self.myCompanies.push(newCompany);
        self.select(newCompany);
        var loc = self.workingCompany() ? self.workingCompany().Location() ? self.workingCompany().Location() : "" : "";
        $.when(loadGoogleMaps(3, null, null))
            .then(function() {
                $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
                    $("#addressCompanyEditMode").gmap3({
                            action: 'getAddress',
                            address: loc,
                            callback: function(results) {
                                if (!results) return;
                                $("#addressCompanyEditMode").gmap3(
                                    { action: 'clear', name: 'marker' },
                                    { action: 'addMarker', latLng: results[0].geometry.location },
                                    { action: 'setCenter', args: [results[0].geometry.location] }
                );
                            }
                        });
                });
            });
        self.workingCompanyId(self.workingCompany().Id());
        self.companyViewMode("edit");
        self.generateRoute();
    };
    self.selectEdit = function(company) {
        self.select(company);
        var loc = self.workingCompany() ? self.workingCompany().Location() ? self.workingCompany().Location() : "" : "";
        $.when(loadGoogleMaps(3, null, null))
            .then(function() {
                $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
                    $("#addressCompanyEditMode").gmap3({
                            action: 'getAddress',
                            address: loc,
                            callback: function(results) {
                                if (!results) return;
                                $("#addressCompanyEditMode").gmap3(
                                    { action: 'clear', name: 'marker' },
                                    { action: 'addMarker', latLng: results[0].geometry.location },
                                    { action: 'setCenter', args: [results[0].geometry.location] }
                );
                            }
                        });
                });
            });
        self.workingCompanyId(self.workingCompany().Id());
        self.companyViewMode("edit");
        self.generateRoute();
    };
    self.selectDetails = function(company) {
        self.select(company);
        var loc = self.workingCompany() ? self.workingCompany().Location() ? self.workingCompany().Location() : "" : "";
        $.when(loadGoogleMaps(3, null, null))
            .then(function() {
                $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
                    $("#addressCompanyDetails").gmap3({
                            action: 'getAddress',
                            address: loc,
                            callback: function(results) {
                                if (!results) return;
                                $("#addressCompanyDetails").gmap3(
                                    { action: 'clear', name: 'marker' },
                                    { action: 'addMarker', latLng: results[0].geometry.location },
                                    { action: 'setCenter', args: [results[0].geometry.location] }
                );
                            }
                        });
                });
            });
        self.workingCompanyId(self.workingCompany().Id());
        self.companyViewMode("details");
        self.generateRoute();
    };
    //SIMPLE SEARCH
    self.simpleSearch = function() {
        self.companyAdvancedSearch().CountryIds([]);
        self.companyAdvancedSearch().CountryIds().push(self.selectedCountryId());
        self.companyAdvancedSearch().IndustryIds([]);
        self.companyAdvancedSearch().IndustryIds().push(self.selectedIndustryId());
        self.generateRoute();
    };

    self.resetAdvancedSearch = function() {
        self.companyAdvancedSearch(new CompanyProfileAdvancedSearch({ }));
        self.keywordTags([]);
        self.countryTags([]);
        self.industryTags([]);
        self.categoryTags([]);
        self.technologyTags([]);
    };

    //LOCATION VISIBILITY
    self.locationVisible = ko.observable(false);
    self.locationMapVisible = ko.observable(false);
    self.isLocationVisible = ko.computed(function() {
        if (self.workingCompany() != null) {
            if (self.workingCompany().Country() != null) {
                self.locationVisible(true);
                if (self.workingCompany().Location() != "") {
                    self.locationMapVisible(true);
                } else {
                    self.locationMapVisible(false);
                }
            } else {
                self.locationVisible(false);
            }
        }
    });

    // CATEGORIES/TECHNOLOGIES VISIBILITY
    self.categoriesTechnologiesVisible = ko.observable(false);
    self.areCategoriesTechnologiesVisible = ko.computed(function() {
        if (self.workingCompany()) {
            if (self.workingCompany().Industry() != null) {
                self.categoriesTechnologiesVisible(true);
            }
        }
    });

    self.nameVisible = ko.observable(true);
    self.isNameVisible = ko.computed(function() {
        if (self.workingCompany() != null) {
            if (self.workingCompany().Title() != null && self.workingCompany().Title() != "") {
                self.nameVisible(false);
            }
        }
    });
    self.descriptionVisible = ko.observable(true);
    self.isDescriptionVisible = ko.computed(function() {
        if (self.workingCompany() != null) {
            if (self.workingCompany().Description() != null && self.workingCompany().Description() != "") {
                self.descriptionVisible(false);
            }
        }
    });

    //COMPANY'S Positions
    self.companyPositions = ko.observableArray([]);
    self.loadCompanyPositions = function(pageIndex, pageSize, industryId, categoryId, technologyId, companyId) {
        $.getJSON("/Position/List", { pageIndex: pageIndex, pageSize: pageSize, industryId: industryId, categoryId: categoryId, technologyId: technologyId, companyId: companyId }, function(allData) {
            self.parent.project.pagesCount(allData.PagesCount);
            self.parent.project.count(allData.Count);
            var mappedPositions = $.map(allData.Entities, function(item) { return new Project(item); });
            self.parent.project.Positions(mappedPositions);
        });
    };

    //CENTER MODALS
    self.initContactCompanyModal = function() {
        $('#ContactCompany').on('shown', function() {
            var modal;
            modal = $(this);
            modal.css('margin-top', (modal.outerHeight() / 2) * -1).css('margin-left', (modal.outerWidth() / 2) * -1);
            return this;
        });
    };

    //COUNTRIES
    self.availableCountries = ko.observableArray([]);
    self.loadCountries = function() {
        $.getJSON("/ExpertProfile/GetJsonCountry", function(countries) {
            self.availableCountries(countries);
        });
    };

    //EDITMODE-EDIT COMPANY
    self.selectName = function() {
        self.workingCompanyBuffer().Title(self.workingCompany().Title());
    };
    self.okName = function() {
        if (self.workingCompanyBuffer().Title.isValid()) {
            self.workingCompany().Title(self.workingCompanyBuffer().Title());
            $("#NameCompanyDialog").modal("hide");
        }
    };
    self.cancelName = function() {
        $("#NameCompanyDialog").modal("hide");
    };
    self.selectDescription = function() {
        self.workingCompanyBuffer().Description(self.workingCompany().Description());
    };
    self.okDescription = function() {
        if (self.workingCompanyBuffer().Description.isValid()) {
            self.workingCompany().Description(self.workingCompanyBuffer().Description());
            self.workingCompany().DescriptionShort($(".tinymceDescriptionCompany").val());
            $("#DescriptionCompanyDialog").modal("hide");
        }
    };
    self.cancelDescription = function() {
        $("#DescriptionCompanyDialog").modal("hide");
    };
    self.selectWebsite = function() {
        self.workingCompanyBuffer().Website(self.workingCompany().Website());
    };
    self.okWebsite = function() {
        if (self.workingCompanyBuffer().Website.isValid()) {
            self.workingCompany().Website(self.workingCompanyBuffer().Website());
            $("#WebsiteCompanyDialog").modal("hide");
        }
    };
    self.cancelWebsite = function() {
        $("#WebsiteCompanyDialog").modal("hide");
    };
    self.selectTagLine = function() {
        self.workingCompanyBuffer().TagLine(self.workingCompany().TagLine());
    };
    self.okTagLine = function() {
        if (self.workingCompanyBuffer().TagLine.isValid()) {
            self.workingCompany().TagLine(self.workingCompanyBuffer().TagLine());
            $("#TagLineCompanyDialog").modal("hide");
        }
    };
    self.cancelTagLine = function() {
        $("#TagLineCompanyDialog").modal("hide");
    };
    self.selectCountry = function() {
        //for update mode
        if (self.workingCompany().Id() != 0) {
            var country = $.Enumerable.From(parent.availableCountriesWithoutAll()).SingleOrDefault(null, function(x) {
                return self.workingCompany().Country().Id === x.Id;
            });
            if (country != null) {
                self.workingCompanyBuffer().Country(country);
            }
            $("#CountryUpdateCompanyDialog").modal("show");
        }
            //for create new mode
        else {
            $("#CountryCompanyDialog").modal("show");
        }
    };
    self.okCountry = function() {
        if (self.workingCompanyBuffer().Country.isValid()) {
            self.workingCompany().Country(self.workingCompanyBuffer().Country());
            //for update mode
            if (self.workingCompany().Id() != 0) {
                $("#CountryUpdateCompanyDialog").modal("hide");
            }
                //for create new mode
            else {
                $("#CountryCompanyDialog").modal("hide");
            }
        }
    };
    self.cancelCountry = function() {
        if (self.workingCompany().Id() != 0) {
            $("#CountryUpdateCompanyDialog").modal("hide");
        }
            //for create new mode
        else {
            $("#CountryCompanyDialog").modal("hide");
        }
    };
    self.selectIndustry = function() {
        //for update mode
        if (self.workingCompany().Id() != 0) {
            var industry = $.Enumerable.From(parent.availableIndustriesWithoutAll()).SingleOrDefault(null, function(x) {
                return self.workingCompany().Industry().Id === x.Id;
            });
            if (industry != null) {
                self.workingCompanyBuffer().Industry(industry);
            }
            $("#IndustryUpdateCompanyDialog").modal("show");
        }
            //for create new mode
        else {
            $("#IndustryCompanyDialog").modal("show");
        }
    };
    self.okIndustry = function() {
        if (self.workingCompanyBuffer().Industry.isValid()) {
            self.workingCompany().Industry(self.workingCompanyBuffer().Industry());
            //for update mode
            if (self.workingCompany().Id() != 0) {
                $("#IndustryUpdateCompanyDialog").modal("hide");
            }
                //for create new mode
            else {
                $("#IndustryCompanyDialog").modal("hide");
            }
        }
    };
    self.cancelIndustry = function() {
        if (self.workingCompany().Id() != 0) {
            $("#IndustryUpdateCompanyDialog").modal("hide");
        }
            //for create new mode
        else {
            $("#IndustryCompanyDialog").modal("hide");
        }
    };
    self.selectAddress = function() {
        $.when(loadGoogleMaps(3, null, null))
            .then(function() {
                $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
                    var loc = self.workingCompany() ? self.workingCompany().Location() ? self.workingCompany().Location() : "" : "";
                    $("#addressAutocompleteCompany").val(loc);
                    $("#addressCompany").gmap3({
                            action: 'getAddress',
                            address: loc,
                            callback: function(results) {
                                if (!results) return;
                                $("#addressCompany").gmap3(
                                    { action: 'clear', name: 'marker' },
                                    { action: 'addMarker', latLng: results[0].geometry.location },
                                    { action: 'setCenter', args: [results[0].geometry.location] },
                                    { action: 'clear', name: 'InfoWindow' },
                                    {
                                        action: 'addInfoWindow',
                                        address: loc,
                                        map: {
                                            center: true,
                                            zoom: 10
                                        },
                                        infowindow: {
                                            options: { content: loc }
                                        }
                                    }
                );
                            }
                        });
                });
            });
        self.gmapAddressAutocomplete();

    };
    self.okAddress = function() {
        var address = $("#addressAutocompleteCompany").val();
        self.workingCompany().Location(address);
        $("#AddressCompanyDialog").modal("hide");
    };
    self.cancelAddress = function() {
        $("#AddressCompanyDialog").modal("hide");
    };
    self.okPhoto = function() {
        if (self.workingCompanyBuffer().Photo.isValid()) {
            self.workingCompany().Photo(self.workingCompanyBuffer().Photo());
            self.resetPhotoUpload();
            $("#PhotoCompanyDialog").modal("hide");
        }
    };
    self.cancelPhoto = function() {
        self.resetPhotoUpload();
        $("#PhotoCompanyDialog").modal("hide");
    };
    self.selectEmail = function() {
        self.workingCompanyBuffer().Email(self.workingCompany().Email());
    };
    self.okEmail = function() {
        if (self.workingCompanyBuffer().Email.isValid()) {
            self.workingCompany().Email(self.workingCompanyBuffer().Email());
            $("#EmailCompanyDialog").modal("hide");
        }
    };
    self.cancelEmail = function() {
        $("#EmailCompanyDialog").modal("hide");
    };
    self.selectPhoneNumber = function() {
        self.workingCompanyBuffer().PhoneNumber(self.workingCompany().PhoneNumber());
    };
    self.okPhoneNumber = function() {
        if (self.workingCompanyBuffer().PhoneNumber.isValid()) {
            self.workingCompany().PhoneNumber(self.workingCompanyBuffer().PhoneNumber());
            $("#PhoneNumberCompanyDialog").modal("hide");
        }
    };
    self.cancelPhoneNumber = function() {
        $("#PhoneNumberCompanyDialog").modal("hide");
    };
    self.selectCategories = function() {
        self.selectCatVisible(true);
        self.selectCatNotVisible(false);
        self.getChildCategories();
        self.workingCompanyBuffer().Categories(self.workingCompany().Categories());
    };
    self.okCategories = function() {
        self.resetCategories();
        self.workingCompany().Categories(self.workingCompanyBuffer().Categories());
        $("#CategoriesCompanyDialog").modal("hide");
    };
    self.cancelCategories = function() {
        self.resetCategories();
        $("#CategoriesCompanyDialog").modal("hide");
    };

    self.selectTechnologies = function() {
        self.loadTechnologies();
        self.workingCompanyBuffer().Technologies(self.workingCompany().Technologies());
    };
    self.okTechnologies = function() {
        self.workingCompany().Technologies(self.workingCompanyBuffer().Technologies());
        $("#TechnologiesCompanyDialog").modal("hide");
    };
    self.cancelTechnologies = function() {
        $("#TechnologiesCompanyDialog").modal("hide");
    };

    //CATEGORIES
    self.selectCatVisible = ko.observable(true);
    self.selectCatNotVisible = ko.observable(false);
    self.availableCategories = ko.observableArray([]);
    self.breadCrumbCategories = ko.observableArray([{ Id: -1, Description: "Start" }]);
    self.getChildCategories = function(category) {
        $.getJSON('/ExpertProfile/GetChildCategories', category, function(result) {
            self.availableCategories(result);
        });
    };
    self.resetCategories = function() {
        self.getChildCategories(null);
        self.breadCrumbCategories([{ Id: -1, Description: "Start" }]);
    };
    self.selectBreadCrumbCategory = function(category) {
        var index = 0;
        var count = self.breadCrumbCategories().length;

        // find the index of the selected bread crumb category
        for (; index < count; index++) {
            if (self.breadCrumbCategories()[index].Id == category.Id) {
                break;
            }
        }
        var deleteCount = count - index - 1;
        //returns the selected category
        if (deleteCount > 0) {
            self.breadCrumbCategories.splice(index + 1, deleteCount);
        }
        self.getChildCategories(category);
    };

    self.addCategory = function(category) {
        if (category.IsLeaf) {
            var foundCategory = ko.utils.arrayFirst(self.workingCompanyBuffer().Categories(), function(item) {
                return item.Id == category.Id;
            });
            if (!foundCategory) {
                self.workingCompanyBuffer().Categories.push(category);
                self.selectCatVisible(false);
                self.selectCatNotVisible(true);
            }
        } else {
            self.breadCrumbCategories.push(category);
            self.getChildCategories(category);
        }
    };

    self.removeCategory = function(category) {
        self.workingCompanyBuffer().Categories.remove(category);
    };

    //TECHNOLOGIES
    self.availableTechnologiesNames = ko.observable([]);
    self.newTechnology = ko.observable();
    self.loadTechnologies = function() {
        $.getJSON("/Position/GetJsonTechnologies", function(technologies) {
            self.availableTechnologiesNames(technologies);
        });
    };
    self.technologyName = ko.observable("");
    self.createAndAddTechnology = function() {
        var newTech = $("#TechnologiesCompanyEditMode").val();
        self.technologyName(newTech);
        $.getJSON("/Position/CreateTechnology", { technologyName: self.technologyName(), industryId: self.workingCompany().Industry().Id }, function(technologyArray) {
            var mappedTechnologies = $.map(technologyArray, function(item) { return new Technology(item); });
            for (var i = 0; i < mappedTechnologies.length; i++) {
                self.workingCompanyBuffer().Technologies.push(mappedTechnologies[i]);
            }
            $("#TechnologiesCompanyEditMode").val("");
        });
    };
    self.removeTechnology = function(technology) {
        self.workingCompanyBuffer().Technologies.remove(technology);
    };
    self.autocompleteTechnologiesEditMode = function() {
        $("#TechnologiesCompanyEditMode").autocomplete({
                source: function(request, response) {
                    $.ajax({
                            url: "Technology/GetTechnologiesAutocomplete",
                            dataType: "json",
                            data: {
                                searchTerm: request.term,
                                maxRows: 8
                            },
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.Name,
                                        value: item.Name
                                    };
                                }));
                            }
                        });
                },
                minLength: 0,
                select: function(event, ui) {
                    var id = ui.item.value;
                    var description = ui.item.label;

                    //                  var found = ko.utils.arrayFirst(self.technologyTags(), function (item) {
                    //                      return item.Description == description;
                    //                  });
                    //                  if (!found) {
                    //                      self.technologyTags.push({ Id: id, Description: description });
                    //                      self.PositionAdvancedSearch().TechnologyIds.push(id);
                    //                  }

                    //                  $("#tSkillProfileEditMode").val("");
                    //                  return false;
                },
                focus: function(event, ui) {
                    this.value = ui.item.label;
                    event.preventDefault(); // Prevent the default focus behavior.
                }
            });
    };

    //CRUD OPERATIONS
    self.alertVisible = ko.observable(false);
    self.tableOfCompaniesVisible = ko.observable(false);
    self.youAreNotAllowedAlertVisible = ko.observable(true);
    self.SaveOrUpdate = function() {
        if (self.workingCompany().errors().length == 0) {
            self.workingCompany().CountryId(self.workingCompany().Country().Id);
            self.workingCompany().IndustryId(self.workingCompany().Industry().Id);
            //self.workingCompany().DescriptionShort($("#tinymceCompanyDescription").text());
            if (self.workingCompany().Id() == 0) {
                $.ajax({
                    url: "/api/CompanyProfile/PostCompanyProfile",
                    type: 'POST',
                    data: ko.toJSON(self.workingCompany()),
                    contentType: 'application/json',
                    statusCode: {
                        201: function (id) {
                            self.selectDetails(self.workingCompany());
                        }
                    }
                });
            } else {
                $.ajax({
                    url: "/api/CompanyProfile/UpdateCompanyProfile",
                    type: 'POST',
                    data: ko.toJSON(self.workingCompany()),
                    contentType: 'application/json',
                    statusCode: {
                        200: function () {
                            self.selectDetails(self.workingCompany());
                        },
                        403: function () {
                            self.tableOfCompaniesVisible(false);
                            self.youAreNotAllowedAlertVisible(true);
                        }
                    }
                });
            }
        } else {
            self.alertVisible(true);
        }
    };
    self.cancelEdit = function() {
        self.loadMyCompany();
        $("#EditCompanyDialog").modal("hide");
    };
    self.deleteCompany = function() {
        $.post("/api/CompanyProfile/DeleteCompanyProfile", { profileId: self.workingCompany().Id() }, function() {
            self.companies.remove(function(item) { return item.Id() == self.workingCompany().Id(); });
            if (self.companyViewMode() == "details") {
                self.companyViewMode("myList");
            }
            $('#DeleteCompanyDialog').modal('hide');
        });

    };
    self.cancelDeleteCompany = function() {
        $('#DeleteCompanyDialog').modal('hide');
    };

    //PAGING
    self.pagesCount = ko.observable(1);
    self.count = ko.observable(0);
    self.lastPage = function() {
        self.companyAdvancedSearch().PageIndex(self.pagesCount() - 1);
        self.generateRoute();
    };
    self.firstPage = function() {
        self.companyAdvancedSearch().PageIndex(0);
        self.generateRoute();
    };
    self.nextPage = function() {
        if (self.companyAdvancedSearch().PageIndex() < self.pagesCount() - 1) {
            self.companyAdvancedSearch().PageIndex(self.companyAdvancedSearch().PageIndex() + 1);
        }
        self.generateRoute();
    };
    self.previousPage = function() {
        if (self.companyAdvancedSearch().PageIndex() > 0) {
            self.companyAdvancedSearch().PageIndex(self.companyAdvancedSearch().PageIndex()() - 1);
        }
        self.generateRoute();
    };
    self.pageNumber = function(number) {
        self.companyAdvancedSearch().PageIndex(number);
        self.generateRoute();
    };
    self.fromPageNumber = ko.computed(function() {
        return (self.companyAdvancedSearch().PageSize() * (self.companyAdvancedSearch().PageIndex() + 1)) - self.companyAdvancedSearch().PageSize() + 1;
    });
    self.toPageNumber = ko.computed(function() {
        return self.companyAdvancedSearch().PageSize() * (self.companyAdvancedSearch().PageIndex() + 1);
    });

    self.pageSize = ko.observable(3);
    self.pageSize.subscribe(function(newValue) {
        self.companyAdvancedSearch().PageSize(newValue);
        if (parent.route() == "companies") {
            self.generateRoute();
        }

    });
    
    self.showAllMyCompanies = function() {
          self.companyAdvancedSearch().ShowAll(true);
          self.loadCompaniesAdvancedSearchAll();
    };
    self.showLessMyCompanies = function () {
        self.companyAdvancedSearch().ShowAll(false);
        self.loadCompaniesAdvancedSearchAll();
    };
    
    //CONTACT COMPANY
    self.email = ko.observable();
    self.subject = ko.observable();
    self.body = ko.observable();
    self.contactSuccessfullVisible = ko.observable(false);
    self.resetContact = function() {
        self.email("");
        self.subject("");
        self.body("");
        self.contactSuccessfullVisible(false);
    };
    self.contactCompany = function() {
        $.post("/CompanyProfile/ContactCompany", { id: self.workingCompany().UserId(), Email: self.email(), Subject: self.subject(), Body: self.body() }, function() {
            self.contactSuccessfullVisible(true);
            setTimeout(function() { $("#ContactCompany").modal("hide"); }, 2500);
        });
    };
    self.cancelContactCompany = function() {
        $("#ContactCompany").modal("hide");
        self.resetContact();
    };
    self.selectCompanyAndReset = function(company) {
        self.workingCompany(company);
        self.resetContact();
        self.initContactCompanyModal();
    };

    //ADVANCED SEARCH
    self.advancedSearch = function() {
        if (self.searchType() == "all") {
            self.loadCompaniesAdvancedSearchAll();
        } else {
            self.loadCompaniesAdvancedSearchSome();
        }
    };

    //SET INDUSTRYID
    self.industryId = ko.observable(0);
    self.setIndustryId = function(industry) {
        self.companyAdvancedSearch().IndustryIds().push(industry.Id);
        self.selectedIndustryId(industry.Id);
        self.generateRoute();
    };
    //SET COUNTRYID
    self.countryId = ko.observable(0);
    self.setCountryId = function(company) {
        self.companyAdvancedSearch().CountryIds().push(company.CountryId());
        self.selectedCountryId(company.CountryId());
        self.generateRoute();
    };

    //Positions
    self.setPositions = function(company) {
        parent.project.projectAdvancedSearch().CompanyProfileIds().push(company.Id());
        parent.project.generateRoute();
    };

    //LIST AND MYLIST
    self.setListRoute = function() {
        self.resetSearchModel();
        self.companyAdvancedSearch().UserId(0);
        self.companyViewMode("list");
        self.generateRoute();
    };
    self.setMyListRoute = function () {
        self.resetSearchModel();
        self.companyAdvancedSearch().UserId(1);
        self.companyViewMode("myList");
        self.loadCompaniesAdvancedSearchAll();
    };

    self.checkLogo = ko.computed(function() {
        if (self.workingCompany()) {
            var photo = self.workingCompany().Photo();
            self.workingCompany().Photo150X150(photo.replace("/250X250_", "/150X150_"));
            self.workingCompany().Photo80X80(photo.replace("/250X250_", "/80X80_"));
        }
    });
    //set profile as default
    self.setAsDefault = function (company) {
        $.ajax({
            url: "/api/CompanyProfile/SetAsDefault",
            type: 'POST',
            dataType: 'json',
            data: ko.toJSON(company),
            contentType: 'application/json',
            statusCode: {
                200: function () {
                    self.setMyListRoute();
                    parent.profile.setMyListRoute();
                    parent.position.setMyListRoute();
                }
            }
        });
    };
    self.userSignedIn = ko.observable(false);
    self.editDeleteNewButton = ko.observable(false);
    self.messageButton = ko.observable(true);
    self.editDeleteNewButtonsVisible = ko.computed(function() {
        var mode = self.companyViewMode();
        //check if user is signed in
        if (mode == "details") {
            if (self.workingCompany().IsAuthenticated()) {
                self.userSignedIn(true);
            }
        }
        if (mode == "myList" || self.userSignedIn() == true) {
            self.editDeleteNewButton(true);
            self.messageButton(false);
        } else {
            self.editDeleteNewButton(false);
            self.messageButton(true);
        }
    });

    //LOAD
    self.loadCompaniesAdvancedSearchAll = function() {
        if (self.companyViewMode() == "list" || self.companyViewMode() == "myList") {
            self.noResultsMessageVisible = ko.observable(false);
            $.ajax({
                url: "/api/CompanyProfile/ListAdvancedSearchAll",
                    type: 'post',
                    data: ko.toJSON(self.companyAdvancedSearch()),
                    contentType: "application/json",
                    success: function(page) {
                        self.pagesCount(page['<PagesCount>k__BackingField']);
                        self.count(page['<Count>k__BackingField']);
                        var mappedCompanies = $.map(page['<Entities>k__BackingField'], function (item) { return new CompanyProfile(item); });
                        self.companies(mappedCompanies);
                    }
                });
        }
    };
    self.loadCompaniesAdvancedSearchSome = function() {
        self.noResultsMessageVisible = ko.observable(false);
        $.ajax({
                url: "/CompanyProfile/ListAdvancedSearchSome",
                type: 'post',
                data: ko.toJSON(self.companyAdvancedSearch()),
                contentType: "application/json",
                success: function(allData) {
                    self.pagesCountCompanies(allData.PagesCount);
                    self.countCompanies(allData.Count);
                    var mappedCompanies = $.map(allData.Entities, function(item) { return new CompanyProfile(item); });
                    self.companies(mappedCompanies);
                }
            });
    };
    self.noResultsMessageVisible = ko.observable(false);
    self.search = function() {
        self.noResultsMessageVisible(false);
        if (self.companyAdvancedSearch().CountryIds().length == 1) {
            self.selectedCountryId(self.companyAdvancedSearch().CountryIds()[0]);
        }
        if (self.companyAdvancedSearch().IndustryIds().length == 1) {
            self.selectedIndustryId(self.companyAdvancedSearch().IndustryIds()[0]);
        }

        $.ajax({
                url: "/CompanyProfile/ListAdvancedSearchAll",
                type: 'post',
                data: ko.toJSON(self.companyAdvancedSearch()),
                contentType: "application/json",
                success: function(allData) {
                    self.pagesCount(allData.PagesCount);
                    self.count(allData.Count);
                    var mappedCompanies = $.map(allData.Entities, function(item) { return new CompanyProfile(item); });
                    self.companies(mappedCompanies);
                    if (self.companies().length == 0) {
                        self.companyViewMode("list");
                        self.tableOfCompaniesVisible(false);
                        self.noResultsMessageVisible(true);
                    } else {
                        self.tableOfCompaniesVisible(true);
                        self.noResultsMessageVisible(false);
                        self.generateRoute();
                    }
                }
            });

    };
    self.resetSimpleSearch = function() {
        self.selectedCountryId(-1);
        self.selectedIndustryId(-1);
        self.companyAdvancedSearch(new CompanyProfileAdvancedSearch({ }));
        self.loadCompaniesAdvancedSearchAll();
    };

    self.setDefaultSidebarIds = function() {
        self.selectedCountryId(-1);
        self.selectedIndustryId(-1);
    };

    //RESET SEARCH MODEL
    self.resetSearchModel = function() {
        self.workingCompanyId(null);
        self.companyViewMode("list");
        self.companyAdvancedSearch().PageIndex(parent.pageIndexDefault);
        self.companyAdvancedSearch().PageSize(parent.pageSizeDefault);
        self.companyAdvancedSearch().IndustryIds([]);
        self.companyAdvancedSearch().CountryIds([]);
    };

    self.generateRoute = function() {
        var id = self.workingCompanyId();
        var mode = self.companyViewMode();
        var pageIndex = self.companyAdvancedSearch().PageIndex();
        var pageSize = self.companyAdvancedSearch().PageSize();
        var industryId = self.companyAdvancedSearch().IndustryIds()[0];
        var countryId = self.companyAdvancedSearch().CountryIds()[0];
        var route = '#/Companies/?';
        var defaultRoute = route;
        if (id != null) {
            route = route + (defaultRoute != route ? '&' : '') + 'id=' + id;
        }
        if (mode != null && mode != "" && mode != "advancedSearch") {
            route = route + (defaultRoute != route ? '&' : '') + 'mode=' + mode;
        }
        if (pageIndex != null && pageIndex != parent.pageIndexDefault && (mode == "list" || mode == "myList")) {
            route = route + (defaultRoute != route ? '&' : '') + 'pageIndex=' + pageIndex;
        }
        if (pageSize != null && pageSize != parent.pageSizeDefault && (mode == "list" || mode == "myList")) {
            route = route + (defaultRoute != route ? '&' : '') + 'pageSize=' + pageSize;
        }
        if (self.companyAdvancedSearch().IndustryIds().length != 0 && self.companyAdvancedSearch().IndustryIds()[0] != -1 && mode != "advancedSearch") {
            route = route + (defaultRoute != route ? '&' : '') + 'industryId=' + industryId;
        }
        if (self.companyAdvancedSearch().CountryIds().length != 0 && self.companyAdvancedSearch().CountryIds()[0] != -1 && mode != "advancedSearch") {
            route = route + (defaultRoute != route ? '&' : '') + 'countryId=' + countryId;
        }
        location.hash = route;
    };


    //UPLOAD LOGO
    self.photo = ko.observable("");
    self.beforePhotoUpload = ko.observable(true);
    self.afterPhotoUpload = ko.observable(false);
    self.photoAlertVisible = ko.observable(false);
    self.uploadPhotoProgressBarVisible = ko.observable(false);
    self.resetPhotoUpload = function() {
        self.beforePhotoUpload(true);
        self.afterPhotoUpload(false);
        self.photoAlertVisible(false);
        self.uploadPhotoProgressBarVisible(false);
        $('#dropZonePhotoCompany').css('background', 'lightgray');
    };
    self.dropPhoto = function() {
        $('#dropZonePhotoCompany').filedrop({
                url: 'Upload/UploadLogo',
                paramname: 'file',
                maxFiles: 1,
                maxfilesize: 5,
                data: { companyId: self.workingCompany().Id() },
                dragOver: function() {
                    $('#dropZonePhotoCompany').css('background', 'white');
                },
                dragLeave: function() {
                    $('#dropZonePhotoCompany').css('background', 'gray');
                },
                drop: function() {
                    $('#dropZonePhotoCompany').css('background', 'gray');
                },
                progressUpdated: function(i, file, progress) {
                    // this function is used for large files and updates intermittently
                    // progress is the integer value of file being uploaded percentage to completion
                    self.uploadPhotoProgressBarVisible(true);
                    $("#uploadPhotoCompanyProgressBar").width(progress + "%");
                    $("#uploadPhotoCompanyProgressBar").width(100 + "%");
                },
                uploadFinished: function(i, file, response, time) {
                    self.workingCompanyBuffer().Photo(response);
                    if (self.workingCompanyBuffer().Photo.isValid()) {
                        $('#uploadPhotoCompanyResult').html('');
                        $('#uploadPhotoCompanyResult').html(file.name);
                        self.photo(response);
                        self.beforePhotoUpload(false);
                        self.afterPhotoUpload(true);
                    } else {
                        self.photoAlertVisible(true);
                    }

                }
            });
    };
    //GMAP
    self.gmapAddressAutocomplete = function() {
        $.when(loadGoogleMaps(3, null, null))
            .then(function() {
                $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
                    $('#addressAutocompleteCompany').autocompleteG({
                            source: function() {
                                $("#addressCompany").gmap3({
                                        action: 'getAddress',
                                        address: $(this).val() + ', ' + self.workingCompany().Country().Description,
                                        callback: function(results) {
                                            if (!results) return;
                                            $('#addressAutocompleteCompany').autocompleteG('display', results, false);
                                        }
                                    });
                                $("#addressCompanyViewMode").gmap3({
                                        action: 'getAddress',
                                        address: $(this).val() + ', ' + self.workingCompany().Country().Description,
                                        callback: function(results) {
                                            if (!results) return;
                                            $('#addressAutocompleteCompany').autocompleteG('display', results, false);
                                        }
                                    });
                                $("#addressCompanyEditMode").gmap3({
                                        action: $(this).val() + ', ' + self.workingCompany().Country().Description,
                                        address: $(this).val(),
                                        callback: function(results) {
                                            if (!results) return;
                                            $('#addressAutocompleteCompany').autocompleteG('display', results, false);
                                        }
                                    });
                            },
                            cb: {
                                cast: function(item) {
                                    return item.formatted_address;
                                },
                                select: function(item) {
                                    $("#addressCompany").gmap3(
                                        { action: 'clear', name: 'marker' },
                                        { action: 'addMarker', latLng: item.geometry.location },
                                        { action: 'setCenter', args: [item.geometry.location] },
                                        { action: 'clear', name: 'InfoWindow' },
                                        {
                                            action: 'addInfoWindow',
                                            address: $(this).val(),
                                            map: {
                                                center: true,
                                                zoom: 10
                                            },
                                            infowindow: {
                                                options: { content: $(this).val() }
                                            }
                                        }
                                      );
                                    $("#addressCompanyViewMode").gmap3(
                                        { action: 'clear', name: 'marker' },
                                        { action: 'addMarker', latLng: item.geometry.location },
                                        { action: 'setCenter', args: [item.geometry.location] });
                                    $("#addressCompanyEditMode").gmap3(
                                        { action: 'clear', name: 'marker' },
                                        { action: 'addMarker', latLng: item.geometry.location },
                                        { action: 'setCenter', args: [item.geometry.location] });
                                }
                            }
                        });
                });
            });

    };

    //AUTOCOMPLETE
    self.autocompleteCountries = function() {
        $("#countriesCompaniesAutocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                            url: "Country/GetCountriesAutocomplete",
                            dataType: "json",
                            data: {
                                searchTerm: request.term,
                                maxRows: 8
                            },
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.TitleTranslation,
                                        value: item.Id
                                    };
                                }));
                            }
                        });
                },
                minLength: 0,
                select: function(event, ui) {
                    var id = ui.item.value;
                    var description = ui.item.label;

                    var found = ko.utils.arrayFirst(self.countryTags(), function(item) {
                        return item.Description == description;
                    });
                    if (!found) {
                        self.countryTags.push({ Id: id, Description: description });
                        self.companyAdvancedSearch().CountryIds.push(id);
                    }

                    $("#countriesCompaniesAutocomplete").val("");
                    return false;
                },
                focus: function(event, ui) {
                    this.value = ui.item.label;
                    event.preventDefault(); // Prevent the default focus behavior.
                }
            });
    };
    self.showAllCountries = function() {
        $("#countriesCompaniesAutocomplete").autocomplete("search", "");
        $("#countriesCompaniesAutocomplete").focus();
    };
    self.removeCountryTag = function(tag) {
        self.countryTags.remove(tag);
        self.companyAdvancedSearch().CountryIds.remove(function(item) { return item == tag.Id; });
    };

    self.autocompleteIndustries = function() {
        $("#industriesCompaniesAutocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                            url: "Industry/GetIndustriesAutocomplete",
                            dataType: "json",
                            data: {
                                searchTerm: request.term,
                                maxRows: 8
                            },
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.Description,
                                        value: item.Id
                                    };
                                }));
                            }
                        });
                },
                minLength: 0,
                select: function(event, ui) {
                    var id = ui.item.value;
                    var description = ui.item.label;

                    var found = ko.utils.arrayFirst(self.industryTags(), function(item) {
                        return item.Description == description;
                    });
                    if (!found) {
                        self.industryTags.push({ Id: id, Description: description });
                        self.companyAdvancedSearch().IndustryIds.push(id);
                    }

                    $("#industriesCompaniesAutocomplete").val("");
                    return false;
                },
                focus: function(event, ui) {
                    this.value = ui.item.label;
                    event.preventDefault(); // Prevent the default focus behavior.
                }
            });
    };
    self.showAllIndustries = function() {
        $("#industriesCompaniesAutocomplete").autocomplete("search", "");
        $("#industriesCompaniesAutocomplete").focus();
    };
    self.removeIndustryTag = function(tag) {
        self.industryTags.remove(tag);
        self.companyAdvancedSearch().IndustryIds.remove(function(item) { return item == tag.Id; });
    };

    self.autocompleteCategories = function() {
        $("#categoriesCompaniesAutocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                            url: "Category/GetCategoriesAutocomplete",
                            dataType: "json",
                            data: {
                                searchTerm: request.term,
                                maxRows: 8
                            },
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.Description,
                                        value: item.Id
                                    };
                                }));
                            }
                        });
                },
                minLength: 0,
                select: function(event, ui) {
                    var id = ui.item.value;
                    var description = ui.item.label;

                    var found = ko.utils.arrayFirst(self.categoryTags(), function(item) {
                        return item.Description == description;
                    });
                    if (!found) {
                        self.categoryTags.push({ Id: id, Description: description });
                        self.companyAdvancedSearch().CategoryIds.push(id);
                    }

                    $("#categoriesCompaniesAutocomplete").val("");
                    return false;
                },
                focus: function(event, ui) {
                    this.value = ui.item.label;
                    event.preventDefault(); // Prevent the default focus behavior.
                }
            });
    };
    self.showAllCategories = function() {
        $("#categoriesCompaniesAutocomplete").autocomplete("search", "");
        $("#categoriesCompaniesAutocomplete").focus();
    };
    self.removeCategoryTag = function(tag) {
        self.categoryTags.remove(tag);
        self.companyAdvancedSearch().CategoryIds.remove(function(item) { return item == tag.Id; });
    };

    self.autocompleteTechnologies = function() {
        $("#technologiesCompaniesAutocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                            url: "Technology/GetTechnologiesAutocomplete",
                            dataType: "json",
                            data: {
                                searchTerm: request.term,
                                maxRows: 8
                            },
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.Name,
                                        value: item.Id
                                    };
                                }));
                            }
                        });
                },
                minLength: 0,
                select: function(event, ui) {
                    var id = ui.item.value;
                    var description = ui.item.label;

                    var found = ko.utils.arrayFirst(self.technologyTags(), function(item) {
                        return item.Description == description;
                    });
                    if (!found) {
                        self.technologyTags.push({ Id: id, Description: description });
                        self.companyAdvancedSearch().TechnologyIds.push(id);
                    }

                    $("#technologiesCompaniesAutocomplete").val("");
                    return false;
                },
                focus: function(event, ui) {
                    this.value = ui.item.label;
                    event.preventDefault(); // Prevent the default focus behavior.
                }
            });
    };
    self.showAllTechnologies = function() {
        $("#technologiesCompaniesAutocomplete").autocomplete("search", "");
        $("#technologiesCompaniesAutocomplete").focus();
    };
    self.removeTechnologyTag = function(tag) {
        self.technologyTags.remove(tag);
        self.companyAdvancedSearch().TechnologyIds.remove(function(item) { return item == tag.Id; });
    };

    self.autocompleteKeywords = function() {

        $("#keywordsCompaniesAutocomplete").autocomplete({
                source: function(request, response) {
                    $.ajax({
                            url: "CompanyProfile/GetKeywordsAutocomplete",
                            dataType: "json",
                            data: {
                                searchTerm: request.term,
                                maxRows: 8
                            },
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.Description,
                                        value: item.Type + item.Id
                                    };
                                }));
                            }
                        });
                },
                minLength: 0,
                select: function(event, ui) {
                    var description = ui.item.label;
                    var type = ui.item.value.substring(0, 2);
                    var id = ui.item.value.substring(2);

                    if (type == "co") {
                        self.countryTags.push({ Id: id, Description: description });
                        self.companyAdvancedSearch().CountryIds.push(id);
                    } else if (type == "in") {
                        self.industryTags.push({ Id: id, Description: description });
                        self.companyAdvancedSearch().IndustryIds.push(id);
                    }
                    if (event.keyCode == 13) {
                        self.enterKeyPressed = true;
                    }
                    $("#keywordsCompaniesAutocomplete").val("");
                    return false;
                },
                focus: function(event, ui) {
                    this.value = ui.item.label;
                    event.preventDefault(); // Prevent the default focus behavior.
                }
            });
    };
    self.addKeywordTag = function() {
        self.keywordTags.push({ Description: self.keyword() });
        self.companyAdvancedSearch().Keywords.push(self.keyword());
        var tag = $.Enumerable.From(self.keywordTags()).SingleOrDefault(null, function(x) {
            return self.keyword() === x.Description;
        });
        //if enter key is not pressed while selection => remove tag from keywordTags
        if (self.enterKeyPressed) {
            self.keywordTags.remove(tag);
            self.companyAdvancedSearch().Keywords.remove(function(item) { return item == self.keyword(); });
        }
        self.enterKeyPressed = false;
        $("#keywordsCompaniesAutocomplete").val("");
        return false;
    };
    self.removeKeywordTag = function(tag) {
        self.keywordTags.remove(tag);
        self.companyAdvancedSearch().Keywords.remove(function(item) { return item == tag.Description; });
    };
}